package com.example.cadmin.controller;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.cadmin.ScheduledTasks.DynamicTaskService;
import com.example.cadmin.ScheduledTasks.Task;
import com.example.cadmin.entity.Host;
import com.example.cadmin.entity.SysParamset;
import com.example.cadmin.service.FileManageService;
import com.example.cadmin.service.HostService;
import com.example.cadmin.service.SysParamsetService;
import com.example.cadmin.utils.Netty.sendCmd;
import com.example.cadmin.utils.ResponseModel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 * 系统参数 前端控制器
 * </p>
 *
 * @author zzsoft
 * @since 2022-09-21
 */
@Slf4j
@Controller
@RequestMapping("/sys/paramset")
public class SysParamsetController {

    @Resource
    private FileManageController fileManageController;
    @Resource
    public HostService hostService;
    @Resource
    public FileManageService fileManageService;
    @Resource
    public com.example.cadmin.utils.Netty.sendCmd sendCmd;
    @Resource
    private DynamicTaskService dynamicTask;
    @Resource
    public SysParamsetService sysParamsetService;
    @Autowired
    private RestTemplateAutoConfiguration restTemplateAutoConfiguration;

    /**
     * 系统参数设置页面
     */
    @GetMapping("/index")
    public ModelAndView setupIndex(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("Setting/paramsIndex");
        modelAndView.addAllObjects(fileManageController.layerColumnFor(request));
        SysParamset sysParamset = sysParamsetService.getById(2);
        modelAndView.addObject("sysParamset", sysParamset);
        return modelAndView;
    }

    /**
     * 指定开灯
     */
    @PostMapping("/lightOn")
    @ResponseBody
    public ResponseModel lightOn(@RequestBody JSONObject data, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String number = (String) session.getAttribute("number");
        Host host = hostService.getOne(new QueryWrapper<Host>().eq("number", number));
        if (host == null) {
            return ResponseModel.fail("未找到主机");
        }
        //发送led打开命令
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("cmd", "led_open");
        map.put("cabinet_id", Convert.toInt(host.getNumber()));
        map.put("led_index", fileManageService.calculateLEDPosition(data.getInt("layer"), data.getInt("column")));
        map.put("led_num", 1);
        String sendMap = JSONUtil.toJsonStr(map);
        sendCmd.send(sendMap, null, host.getIp());
        return ResponseModel.success("开灯成功");
    }

    /**
     * 指定关灯
     */
    @PostMapping("/turnOffTheLights")
    @ResponseBody
    public ResponseModel turnOffTheLights(@RequestBody JSONObject data, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String number = (String) session.getAttribute("number");
        Host host = hostService.getOne(new QueryWrapper<Host>().eq("number", number));
        if (host == null) {
            return ResponseModel.fail("未找到主机");
        }
        //发送led打开命令
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("cmd", "led_close");
        map.put("cabinet_id", Convert.toInt(host.getNumber()));
        map.put("led_index", fileManageService.calculateLEDPosition(data.getInt("layer"), data.getInt("column")));
        map.put("led_num", 1);
        String sendMap = JSONUtil.toJsonStr(map);
        sendCmd.send(sendMap, null, host.getIp());
        return ResponseModel.success("关灯成功");
    }


    /**
     * 关闭所有灯
     */
    @GetMapping("/turnOffAllLights")
    @ResponseBody
    public ResponseModel turnOffAllLights(HttpServletRequest request) throws InterruptedException {
        HttpSession session = request.getSession();
        String number = (String) session.getAttribute("number");
        Host host = hostService.getOne(new QueryWrapper<Host>().eq("number", number));
        if (host == null) {
            return ResponseModel.fail("未找到主机");
        }

        //发送led打开命令
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("cmd", "led_close_all");
        String sendMap = JSONUtil.toJsonStr(map);
        sendCmd.send(sendMap, null, host.getIp());
        Thread.sleep(200);
        return ResponseModel.success("关灯成功");
    }

    /**
     * 打开所有灯
     */
    @GetMapping("/turnOnAllLights")
    @ResponseBody
    public ResponseModel turnOnAllLights(HttpServletRequest request) throws InterruptedException {
        HttpSession session = request.getSession();
        String number = (String) session.getAttribute("number");
        Host host = hostService.getOne(new QueryWrapper<Host>().eq("number", number));
        if (host == null) {
            return ResponseModel.fail("未找到主机");
        }
        for (int i = 1; i <= Convert.toInt(host.getNumberOfLayers()); i++) {
            for (int j = 1; j <= Convert.toInt(host.getNumberOfColumns()); j++) {
                //发送led打开命令
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("cmd", "led_open");
                map.put("cabinet_id", Convert.toInt(host.getNumber()));
                map.put("led_index", fileManageService.calculateLEDPosition(i, j));
                map.put("led_num", 1);
                String sendMap = JSONUtil.toJsonStr(map);
                sendCmd.send(sendMap, null, host.getIp());
                Thread.sleep(200);
            }

        }
        return ResponseModel.success("关灯成功");
    }

    /**
     * 保存秒数
     * @param data
     * @return
     */
    @PostMapping("/second/save")
    @ResponseBody
    public ResponseModel secondSave(@RequestBody JSONObject data) {
        if (StrUtil.isEmpty(data.getStr("second"))) {
            return ResponseModel.fail("请输入正确的秒数");
        }
        SysParamset sysParamset = sysParamsetService.getById(2);
        sysParamset.setParamValue(data.getStr("second"));
        boolean status = sysParamsetService.updateById(sysParamset);
        return status ? ResponseModel.success("修改成功") : ResponseModel.fail("修改失败");
    }
}
